package com.one.common.utils;

import android.animation.ValueAnimator;
import android.view.View;
import android.view.ViewGroup;

public class AnimatorUtil {

    /**
     * 使用动画的方式来改变高度解决visible不一闪而过出现
     *
     * @param view
     * @param start 初始状态值
     * @param end   结束状态值
     * @return
     */
    public static ValueAnimator createDropAnim(final View view, int start, int end) {
        ValueAnimator va = ValueAnimator.ofInt(start, end);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();//根据时间因子的变化系数进行设置高度
                ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                layoutParams.height = value;
                view.setLayoutParams(layoutParams);//设置高度
            }
        });
        return va;
    }

    /**
     * 将view从不可见变为可见的动画，原理:动态改变其LayoutParams.height的值
     *
     * @param view 要展示动画的view
     */
    public static void visibleAnimator(final View view) {
        if (view != null) {
            int viewHeight = view.getHeight();
            if (viewHeight == 0) {
                int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                view.measure(width, height);
                viewHeight = view.getMeasuredHeight();
            }
            ValueAnimator animator = ValueAnimator.ofInt(0, viewHeight);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    ViewGroup.LayoutParams params = view.getLayoutParams();
                    params.height = (int) animation.getAnimatedValue();
                    view.setLayoutParams(params);
                }
            });
            animator.start();
        }
    }
}
